package com.lmscn.lms.api.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class PasswordEncoder {
	private String bytesToHex(byte[] b) {
		char[] hexDigit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9','a', 'b', 'c', 'd', 'e', 'f' };

		StringBuffer buf = new StringBuffer();
		for (int j = 0; j < b.length; ++j) {
			buf.append(hexDigit[(b[j] >> 4 & 0xF)]);
			buf.append(hexDigit[(b[j] & 0xF)]);
		}
		return buf.toString();
	}
	public String encode(CharSequence rawPassword) {
		if (rawPassword == null) {
			return null;
		}

		try {
			MessageDigest messageDigest = MessageDigest.getInstance("MD5");
			messageDigest.update(rawPassword.toString().getBytes());

			return bytesToHex(messageDigest.digest());//.substring(8, 24);
		} catch (NoSuchAlgorithmException e) {
			throw new SecurityException(e.getMessage());
		}
	}
	public boolean matches(CharSequence rawPassword, String encodedPassword) {
		return encode(rawPassword).equals(encodedPassword);
	}
	
	public static void main(String[] args) {
		String encodePassword = new PasswordEncoder().encode("111111");
		System.out.println(encodePassword);
	}
}
